package cn.com.kblog.model;


import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.kblog.common.Result;
import cn.com.kblog.util.HtmlFilter;

import com.jfinal.ext.plugin.tablebind.TableBind;
import com.jfinal.kit.StringKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
/**BLOG表
		id	
		title	
		content	
		view_count	
		blog_type
		share_url
		status	
		isTop	
		create_time	
		update_time	
 */

/**
 * Blog Model
 * @author KK.Luo
 * Email luokai8@vip.qq.com
 * @date 2013-11-27下午8:07:26
 */
@TableBind(tableName = "blog",pkName = "id")
public class Blog extends Model<Blog>{
	private static final long serialVersionUID = 7172697867526406976L;
	public static final Blog dao = new Blog();
	
	/**标题 */
	public static final String TITLE = "title";
	/**点击数 */
	public static final String VIEW_COUNT = "view_count";
	/**正文 */
	public static final String CONTENT = "content";
	/**博客类型 */
	public static final String BLOG_TYPE = "blog_type";
	/**发布状态 */
	public static final String STATUS = "status";
	/**是否置顶 */
	public static final String IS_TOP = "isTop";
	/**创建时间 */
	public static final String CREATE_TIME = "create_time";
	/**更新时间 */
	public static final String UPDATE_TIME = "update_time";
	/**关联的Tag_id */
	public static final String TAG_ID = "tag_id";
	
	/**暂存 */
	public static final String STATUS_0 = "0";
	/**发布 */
	public static final String STATUS_1 = "1";
	/**置顶 */
	public static final String IS_TOP_YES = "1";
	/**不置顶 */
	public static final String IS_TOP_NO = "0";
	
	/**
	 * 根据参数返回Blog列表
	 * @param cpage
	 * @param pageSize
	 * @param orderField
	 * @param orderDirection
	 * @param allParams
	 * @return
	 */
	public Page<Blog> pageQuery(int cpage, int pageSize, String orderField,
		String orderDirection, Map<String, String> allParams) {
		String sql_select = "select * ";
		StringBuffer conf = new StringBuffer("from (select distinct t.* from blog t left join blog_tag t1 on t.id=t1.blog_id where 1=1 ");
		List<String> params = new ArrayList<String>();
		if (allParams == null) {
		    allParams = new HashMap<String, String>();
		}
		if (StringKit.notBlank(allParams.get("title"))) {
		    conf.append(" and lower(t.title) like ? ");
		    params.add("%"+allParams.get("title")+"%");
		}
		if (StringKit.notBlank(allParams.get("content"))) {
		    conf.append(" and lower(t.content) like ? ");
		    params.add("%"+allParams.get("content")+"%");
		}
		if (StringKit.notBlank(allParams.get("status"))) {
		    conf.append(" and t.status=? ");
		    params.add(allParams.get("status"));
		}
		if (StringKit.notBlank(allParams.get("isTop"))) {
		    conf.append(" and t.isTop = ? ");
		    params.add(allParams.get("isTop"));
		}
		if (StringKit.notBlank(allParams.get("blog_type"))) {
		    conf.append(" and t.blog_type = ? ");
		    params.add(allParams.get("blog_type"));
		}
		if (StringKit.notBlank(allParams.get("tag_id"))) {
		    conf.append(" and t1.tag_id = ? ");
		    params.add(allParams.get("tag_id"));
		}
		if (StringKit.notBlank(orderField, orderDirection)) {
		    conf.append(" order by ").append(" t.").append(orderField).append(
			    " ").append(orderDirection);
		}
		conf.append(") s");
		return dao.paginate(cpage, pageSize, sql_select, conf.toString(),params.toArray());
	 }
	
	/**
	 * 按关键字查询您Blog 范围：title、content、blog_type、tag_name
	 * @param keywords
	 * @return
	 */
	public Page<Blog> pageQueryByKeywords(int cpage, int pageSize, String orderField,
			String orderDirection,String keywords){
		String sql_select = "select * ";
		StringBuffer conf = new StringBuffer("from (select distinct t.* from blog t " +
				"left join blog_tag t1 on t.id=t1.blog_id " +
				"left join blog_type t2 on t.blog_type=t2.id " +
				"left join tag t3 on t1.tag_id=t3.id where ");
		//分解关键字
		String[]keys = keywords.trim().split("\\s+");
		StringBuffer keysql = new StringBuffer();
		for(String key:keys){
			keysql.append("%"+key);
		}
		keysql.append("%");
		conf.append(" lower(t.title) like ?");
		conf.append(" or lower(t.content) like ?");
		conf.append(" or lower(t2.type_name) like ?");
		conf.append(" or lower(t3.tag_name) like ?");
		conf.append(") s");
		
		return dao.paginate(cpage, pageSize, sql_select, conf.toString()
				,keysql.toString(),keysql.toString(),keysql.toString(),keysql.toString());
		
	}
	
	
	/**
	 * 保存或者更新
	 * @return
	 */
	public Result saveOrUpdate(List<String> tagIds){
		Result result = new Result();
		//更新时间
		this.set(UPDATE_TIME, new java.sql.Timestamp(Calendar.getInstance()
				.getTimeInMillis()));
		//保存
		if (getID() == null) {
	
		   if(this.save()){
			    result.success("添加博客成功！"); 
		   }else{
			    result.error("添加博客失败！");
		   }
		} else {
		//更新
		   if(update()){
			   result.success("更新博客成功！"); 
		   }else{
			   result.error("更新博客失败！");
		   }
		}
		_saveTags(this.getID(), tagIds);
		return result;
	}
	
	
	/**
	 * 根据BlogID 列出所有Tag
	 * 
	 * @return
	 */
	public List<Tag> getTags(){
		String sql = "select t.* from tag t,blog_tag t1 where t.id=t1.tag_id and t1.blog_id=?";
		return Tag.dao.find(sql, this.getID());
	}
	
	
	/**
	 * 保存或者更新Tag与Blog的关系
	 * @return
	 */
	private boolean _saveTags(Integer blogId,List<String> tagIds){
		if(tagIds==null||tagIds.size()==0){
			return true;
		}
		//先删除原有关系
		String sql = "delete from blog_tag where blog_id=?";
		Db.update(sql, blogId);
		
		//依次添加tag_blog
		List<String> sqlList = new ArrayList<String>();
		for (String tagId : tagIds) {
			String sql2 = "insert into blog_tag(blog_id,tag_id) values("+blogId+","+tagId+")";
			sqlList.add(sql2);
		}
		int[] result = Db.batch(sqlList, sqlList.size());
		long updateCount = 0;
		for (int i : result)
		  updateCount += i;
		return updateCount==sqlList.size();
	}
	
	/**
	 * 根据BlogID删除Blog和Tag的关系
	 * @param blogId
	 * @return
	 */
	private Integer _deleteTagsByBlogId(Integer blogId){
    	String sql = "delete from blog_tag where blog_id=?";
    	return Db.update(sql, blogId);
    }
	
    /**
     * 根据ID删除Blog
     * @param id
     * @return
     */
    public Result deleteById(String id) {
    	Result result = new Result();
    	
		if (StringKit.isBlank(id)) {
		     result.success("信息错误！");
		}
		_deleteTagsByBlogId(new Integer(id));
		 if(super.deleteById(id)){
			  result.success("删除博客成功！"); 
		 }else{
			  result.error("删除博客失败！");
		 }
		return result;
    }
    /**
     * 获得博客摘要
     * @return
     */
    public String getAbstract(){
    	String content  = HtmlFilter.getText(this.getStr(Blog.CONTENT)).replace("\\s", "");
    		if(content.length()>200){
    			return content.substring(0,200)+"...";
    		}else {
				return content;
			}
    }
    
    /**
     * 获得博客类型
     * @return
     */
    public BlogType getBlogType(){
    	BlogType type = BlogType.dao.findById(this.get(BLOG_TYPE));
    	return type;
    }
    
    /**
     * view count + 1;
     */
    public boolean addCount(){
    	this.set(Blog.VIEW_COUNT, this.getInt(Blog.VIEW_COUNT)+1);
    	return update();
    }
    
    /**
     * 热门文章
     * @return
     */
    public List<Blog> listTopView(){
    	String sql = "select * from blog order by view_count desc limit 5";
    	return dao.find(sql);
    }
	public Integer getID() {
		return getInt("id");
	} 
}
